package com.whc.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.whc.common.to.es.SkuEsModel;
import com.whc.search.config.GuliESConfig;
import com.whc.search.constant.EsConstant;
import com.whc.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * @author angaoen
 */
@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    /**
     * 高级 REST 客户端。
     */
    @Resource
    private RestHighLevelClient restHighLevelClient;

    /**
     * 上架商品
     *
     * @param skuEsModels 上架商品列表
     * @return 是否有错误
     * @throws IOException 异常
     */
    @Override
    public Boolean productSaveService(List<SkuEsModel> skuEsModels) throws IOException {
        // 批量请求包含有序的IndexRequest 、 DeleteRequest和UpdateRequest ，并允许在单个批次中执行它。
        BulkRequest bulkRequest = new BulkRequest(EsConstant.PRODUCT_INDEX);

        for (SkuEsModel skuEsModel : skuEsModels) {
            IndexRequest request = new IndexRequest();
            request.source(JSON.toJSONString(skuEsModel), XContentType.JSON);
            bulkRequest.add(request);
        }

        // 使用批量 API 执行批量请求。
        BulkResponse response = restHighLevelClient.bulk(bulkRequest, GuliESConfig.COMMON_OPTIONS);
        log.error("执行批量操作出现错误：{}", response.buildFailureMessage());
        // 执行中是否有任何失败。
        return response.hasFailures();
    }
}
